import { watch } from 'vue'
import { debounce } from 'lodash-es'
import { loadMoreMethod } from '@/modules/AutoGrid/tool'

export const infiniteScroll = {
  mounted(el: any, binding: any) {
    const { col, row, grid, emit } = binding.value
    col._query = {
      page: 1,
      size: 20,
      total: 0
    }
    // 查询关键字变化时，重置滚动条
    watch(
      () => col._query?.qs,
      (v: any) => {
        const dropdown = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        if (dropdown) {
          dropdown.scrollTop = 0
        }
      }
    )
    // 加载
    const debounceLoad = debounce(function () {
      loadMoreMethod(col, row, grid)
    }, 200)
    // 滚动事件
    el._handleScroll = (e: any) => {
      const dropdown = e.target
      const scrollTop = dropdown.scrollTop
      const scrollHeight = dropdown.scrollHeight
      const clientHeight = dropdown.clientHeight
      const isBottom = scrollTop + clientHeight >= scrollHeight - 10
      if (isBottom) {
        debounceLoad()
      }
    }
    el._handleKeydown = (e: any) => {
      if (e.code === 'Enter' && emit) {
        emit('enter', e.target, col)
      }
    }
    // 下拉框挂载后，添加滚动事件
    const observer = new MutationObserver((mutationsList, observer) => {
      for (const mutation of mutationsList) {
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          const dropdown = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
          if (dropdown) {
            dropdown.addEventListener('scroll', el._handleScroll)
            observer.disconnect()
          }
          const input = el.querySelector('input')
          if (input) {
            input.addEventListener('keydown', el._handleKeydown)
          }
        }
      }
    })

    observer.observe(document.body, {
      childList: true,
      subtree: true
    })

    el._mutationObserver = observer
  },
  unmounted(el: any) {
    const dropdown = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    if (dropdown) {
      dropdown.removeEventListener('scroll', el._handleScroll)
    }
    const input = el.querySelector('input')
    if (input) {
      input.removeEventListener('keydown', el._handleKeydown)
    }
    if (el._mutationObserver) {
      el._mutationObserver.disconnect()
      delete el._mutationObserver
    }
  }
}
